﻿using AutoMapper;
using iWareModels;
using XiangziProjectTemplete.Core.Api.Common;
using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.IRepository.UnitOfWork;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Enums.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Model.PostParamModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Model.Views;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// XiangziProjectTemplete物流控制器 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LESController : ControllerBase
    {
        private readonly ILes_AgvTaskServices _agvTaskServices;
        private readonly IV_StationServices _V_StationServices;
        private readonly IV_CodeItemsServices _v_CodeItemsServices;
        private readonly ILogger<LESController> _logger;
        private readonly IUser _user;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMapper _autoMapper;
        private readonly ILes_AgvWarningServices _les_AgvWarningServices;
        private readonly IThingworx_CallOrderServices _Thingworx_CallOrderServices;
        private readonly IBase_CodeItemsServices _base_CodeItemsServices;
        private readonly IBase_StationServices _base_StationServices;
        private readonly IV_LES_BufferStockCollectByStationServices _v_LES_BufferStockCollectByStationServices;
        private readonly IV_AgvServices _v_AgvServices;
        private readonly ILes_AgvWarningServices _Les_AgvWarningServices;

        public LESController(
            ILes_AgvWarningServices Les_AgvWarningServices,
             IV_AgvServices v_AgvServices,
            IV_LES_BufferStockCollectByStationServices v_LES_BufferStockCollectByStationServices,
            IBase_StationServices base_StationServices,
            IBase_CodeItemsServices base_CodeItemsServices,
            IThingworx_CallOrderServices Thingworx_CallOrderServices,
            ILes_AgvWarningServices les_AgvWarningServices,
            IV_CodeItemsServices v_CodeItemsServices, IV_StationServices V_StationServices,
             ILogger<LESController> logger, IUser user, IUnitOfWork unitOfWork, ILes_AgvTaskServices agvTaskServices,
             IMapper mapper)
        {
            _Les_AgvWarningServices = les_AgvWarningServices;
            _v_AgvServices = v_AgvServices;
            _v_LES_BufferStockCollectByStationServices = v_LES_BufferStockCollectByStationServices;
            _base_StationServices = base_StationServices;
            _base_CodeItemsServices = base_CodeItemsServices;
            _Thingworx_CallOrderServices = Thingworx_CallOrderServices;
            this._les_AgvWarningServices = les_AgvWarningServices;
            _v_CodeItemsServices = v_CodeItemsServices;
            _V_StationServices = V_StationServices;
            _logger = logger;
            _unitOfWork = unitOfWork;
            _user = user;
            _agvTaskServices = agvTaskServices;
            _autoMapper = mapper;
        }

        #region Thingworx专用


        /// <summary> 
        /// 新增Thingworx发送的呼叫任务  【Thingworx专用】
        /// </summary> 
        /// <param name="request">要新增的Thingworx发送的呼叫任务对象</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<string>> ReqFeed([FromBody] Thingworx_CallOrder request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Thingworx_CallOrder, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                     new ValidateModel(){ ChinaName="任务类型",PropertyName="TaskType" },
                     new ValidateModel(){ ChinaName="工序",PropertyName="Procedure" },
                     new ValidateModel(){ ChinaName="工位号",PropertyName="WorkStationNo" },
                     new ValidateModel(){ ChinaName="点位",PropertyName="StationCode" },
                     new ValidateModel(){ ChinaName="任务号",PropertyName="WorkNo" },
                     new ValidateModel(){ ChinaName="物料",PropertyName="Material" },
                };
                retBody = ValidateDataHelper.CommonValidate<Thingworx_CallOrder, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                //根据工序编号获取工序的码表项ID
                MessageModel<Base_CodeItems> messageModelForPrdcedure = await _base_CodeItemsServices.GetSingleCodeItemByCode(request.Procedure);
                if (messageModelForPrdcedure.success == false)
                {
                    return MessageModel<string>.Fail("根据工序编号" + request.Procedure + "获取工序失败:" + messageModelForPrdcedure.msg);
                }
                if (messageModelForPrdcedure.response == null)
                {
                    return MessageModel<string>.Fail("根据工序编号" + request.Procedure + "没有获取到工序");
                }
                //根据物料编号获取物料的码表项ID
                MessageModel<Base_CodeItems> messageModelForMaterial = await _base_CodeItemsServices.GetSingleCodeItemByCode(request.Material);
                if (messageModelForMaterial.success == false)
                {
                    return MessageModel<string>.Fail("根据物料编号" + request.Material + "获取物料失败:" + messageModelForMaterial.msg);
                }
                if (messageModelForMaterial.response == null)
                {
                    return MessageModel<string>.Fail("根据物料编号" + request.Material + "没有获取到物料");
                }
                //根据站点编号获取站点ID

                List<Base_Station> stationList = await _base_StationServices.Query(x => x.StationCode == request.StationCode);
                if (stationList == null || stationList.Count == 0)
                {
                    return MessageModel<string>.Fail("根据站点编号" + request.StationCode + "没有获取到站点");
                }
                if (stationList.Count > 1)
                {
                    return MessageModel<string>.Fail("根据站点编号" + request.StationCode + "获取到" + stationList.Count + "条站点数据!");
                }

                //转换成Les_CallOrder
                Les_CallOrder callOrder = new Les_CallOrder()
                {
                    LesTaskMode = request.LesTaskMode,
                    AllowProcedure = messageModelForPrdcedure.response.Id.ToString(),
                    StationId = stationList[0].Id,
                    BurdenWorkNo = request.BurdenWorkNo,
                    MaterialCodeItemId = messageModelForMaterial.response.Id.ToString(),
                };
                //验证是否满足条件
                string requestStr = JsonConvert.SerializeObject(callOrder);
                MessageModel<string> messageModel = await WcfService.ValidateCreateCallOrder(requestStr);
                if (messageModel.success == false)
                {
                    return messageModel;
                }
                //创建呼叫订单
                MessageModel<string> messageModelForCall = await WcfService.CreateCallOrder(callOrder, request, "Thingworx", 0);
                if (messageModelForCall.success)
                {
                    return MessageModel<string>.Success("成功", messageModelForCall.response);
                }
                else
                {
                    return MessageModel<string>.Fail("添加失败:" + messageModelForCall.msg);
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增Thingworx发送的呼叫任务出现异常:" + ex.Message);
                return MessageModel<string>.Fail("新增Thingworx发送的呼叫任务出现异常:" + ex.Message);
            }
        }


        /// <summary>
        /// 送料状态查询  【Thingworx专用】
        /// </summary>
        /// <param name="orderId">送料任务ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<string>> QueryOrder(string orderId)
        {
            try
            {
                #region 验证 
                if (string.IsNullOrEmpty(orderId))
                {
                    return MessageModel<string>.Fail("送料任务ID为空");
                }
                #endregion

                //查询订单
                var orders = await _Thingworx_CallOrderServices.Query(x => x.CallOrderTaskNo == orderId);
                if (orders == null || orders.Count == 0)
                {
                    return MessageModel<string>.Fail("根据送料任务ID" + orderId + "没有获取到送料任务");
                }
                if (orders.Count > 1)
                {
                    return MessageModel<string>.Fail("根据送料任务ID" + orderId + "获取到" + orders.Count + "条送料任务!");
                }
                return MessageModel<string>.Success(orders[0].StatusName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "送料状态查询出现异常:" + ex.Message);
                return MessageModel<string>.Fail("送料状态查询出现异常:" + ex.Message);
            }
        }

        #endregion


        /// <summary>
        /// 接受AGV任务的任务状态
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<bool>> SendAgvTaskStatus([FromBody] Les_AgvTask param)
        {
            #region 验证

            if (param == null || param.Id != string.Empty)
            {
                return new MessageModel<bool>()
                {
                    msg = "任务号不能为0",
                    success = false,
                    response = false
                };
            }
            if (param.TaskStatus == Convert.ToInt32(TaskStatusEnum.已下发))
            {
                return await StartAgvTask(param);
            }
            else
            {
                return new MessageModel<bool>()
                {
                    msg = "推送的状态不正确",
                    success = false,
                    response = false
                };
            }
            #endregion
        }

        /// <summary>
        /// 开始AGV任务
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private async Task<MessageModel<bool>> StartAgvTask([FromBody] Les_AgvTask param)
        {
            if (param == null || param.Id != string.Empty)
            {
                return new MessageModel<bool>()
                {
                    msg = "任务号不能为0",
                    success = false,
                    response = false
                };
            }
            try
            {
                Les_AgvTask task = await _agvTaskServices.QueryById(param.Id);
                if (task == null)
                {
                    return new MessageModel<bool>()
                    {
                        msg = "没有找到该任务",
                        success = false,
                        response = false
                    };
                }
                task.ModifyBy = "WCS";
                task.ModifyId = 0;
                task.ModifyTime = DateTime.Now;
                task.OperationRemark = "WCS通知任务已下发";
                task.TaskStatus = Convert.ToInt32(TaskStatusEnum.已下发);
                await _agvTaskServices.Update(task);
                return new MessageModel<bool>()
                {
                    msg = "成功",
                    success = true,
                    response = true
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("WCS通知任务已下发操作失败", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }

        /// <summary>
        /// AGV任务完成 【无权限】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<MessageModel<bool>> FinishAgvTask([FromBody] Les_AgvTaskFinishParam param)
        {
            if (param == null)
            {
                return new MessageModel<bool>()
                {
                    msg = "任务号不能为空",
                    success = false,
                    response = false
                };
            }
            try
            {
                Les_AgvTask task = await _agvTaskServices.GetAgvTaskByTaskNo(param.TaskNo);
                if (task == null)
                {
                    return new MessageModel<bool>()
                    {
                        msg = "没有找到该任务",
                        success = false,
                        response = false
                    };
                }
                task.ModifyBy = "AGV";
                task.ModifyId = 0;
                task.ModifyTime = DateTime.Now;
                task.OperationRemark = "AGV通知任务已完成";
                task.TaskStatus = Convert.ToInt32(TaskStatusEnum.已完成);
                await _agvTaskServices.Update(task);
                return new MessageModel<bool>()
                {
                    msg = "成功",
                    success = true,
                    response = true
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("AGV通知任务已下发操作失败", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }

        /// <summary>
        /// 创建 分拣出库任务，供手持机使用
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<bool>> CreateSortOutStoreTask([FromBody] LES_SortOutStoreTaskPostParam param)
        {
            if (param == null)
            {
                return new MessageModel<bool>()
                {
                    msg = "内容不能为空",
                    success = false,
                    response = false
                };
            }
            try
            {
                bool result = await _agvTaskServices.CreateSortOutStoreTask(param, _user, _unitOfWork);
                return new MessageModel<bool>()
                {
                    msg = "成功",
                    success = true,
                    response = result
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("创建分拣出库任务失败", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }


        /// <summary>
        /// 创建 回库搬运任务，供手持机使用
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<bool>> CreateBackStoreTask([FromBody] LES_SortOutStoreTaskPostParam param)
        {
            if (param == null)
            {
                return new MessageModel<bool>()
                {
                    msg = "内容不能为空",
                    success = false,
                    response = false
                };
            }
            try
            {
                bool result = await _agvTaskServices.CreateaBackStoreTask(param, _user, _unitOfWork);
                return new MessageModel<bool>()
                {
                    msg = "成功",
                    success = true,
                    response = result
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("创建分拣出库任务失败", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }


        /// <summary> 
        /// 接受AGV报警信息 
        /// </summary> 
        /// <param name="requestList">要新增的AGV报警对象集合</param> 
        /// <returns></returns> 
        [HttpPost]
        public async Task<MessageModel<bool>> AddAgvWarning([FromBody] List<AgvWarningPostParam> requestList)
        {
            try
            {
                #region 验证 
                MessageModel<bool> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<List<AgvWarningPostParam>, bool>(requestList);
                if (retBody != null)
                {
                    return retBody;
                }

                #endregion

                return await _les_AgvWarningServices.AddAgvWarning(_unitOfWork, requestList);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理AGV报警出现异常:" + ex.Message);
                return MessageModel<bool>.Fail("处理AGV报警出现异常:" + ex.Message);
            }
        }



        #region 大屏展示专用

        /// <summary> 
        /// 获取Agv车辆全部实时状态信息  【大屏展示专用】
        /// </summary> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<V_Agv>>> GetAllVehicles()
        {
            var dataList = await _v_AgvServices.Query();
            dataList = dataList.OrderBy(x => x.AgvName).ToList();
            return new MessageModel<List<V_Agv>>()
            {
                msg = "获取成功",
                success = true,
                response = dataList
            };
        }

        /// <summary> 
        /// 获取 未关闭的AGV报警    【大屏展示专用】
        /// </summary> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<List<Les_AgvWarning>>> GetLastOneAgvWarning()
        {
            List<Les_AgvWarning> warnList = await _Les_AgvWarningServices.Query(x => x.Status == 0);
            if (warnList == null || warnList.Count == 0)
            {
                return new MessageModel<List<Les_AgvWarning>>()
                {
                    msg = "获取成功",
                    success = true,
                    response = null
                };
            }
            var obj = warnList.OrderByDescending(x => x.CreateTime).ToList();
            return new MessageModel<List<Les_AgvWarning>>()
            {
                msg = "获取成功",
                success = true,
                response = obj
            };
        }


        /// <summary>
        /// 获取 立库缓存区库存列表，为可视化页面专用 【大屏展示专用】
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<V_LES_BufferStockCollectByStation>>> GetStockForBufferStockVisual()
        {
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == StoreAreaEnum.StoreBuffer.ToString());
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }

            List<V_LES_BufferStockCollectByStation> newList = new List<V_LES_BufferStockCollectByStation>();
            //第一排
            var _list = LesApiCommon.GetDataByRow(1, 10, data);
            newList.AddRange(_list);
            //第二排
            _list = LesApiCommon.GetDataByRow(11, 20, data);
            newList.AddRange(_list);
            //第三排
            _list = LesApiCommon.GetDataByRow(21, 30, data);
            newList.AddRange(_list);
            //第四排
            _list = LesApiCommon.GetDataByRow(31, 40, data);
            newList.AddRange(_list);
            //第五排
            _list = LesApiCommon.GetDataByRow(41, 50, data);
            newList.AddRange(_list);
            //第六排
            _list = LesApiCommon.GetDataByRow(51, 60, data);
            newList.AddRange(_list);
            //第七排
            _list = LesApiCommon.GetDataByRow(61, 70, data);
            newList.AddRange(_list);

            return new MessageModel<List<V_LES_BufferStockCollectByStation>>()
            {
                msg = "获取成功",
                success = true,
                response = newList
            };
        }

        /// <summary> 
        /// 获取指定库位区域的库存信息 【大屏展示专用】
        /// </summary> 
        /// <param name="storeAreaCode">库存区域编号</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        //注意：必须要加权限，不然一直刷新但是token不延时 【Editby shaocx,2021-10-18】
        //[AllowAnonymous]
        public async Task<MessageModel<List<V_LES_BufferStockCollectByStation>>> GetStockByArea(string storeAreaCode)
        {
            var data = await _v_LES_BufferStockCollectByStationServices.Query(x => x.StoreAreaCode == storeAreaCode);
            foreach (var item in data)
            {
                item.Station_ModifyTimeStr = DateTimeHelper.ConvertToString(item.Station_ModifyTime);
            }
            return new MessageModel<List<V_LES_BufferStockCollectByStation>>()
            {
                msg = "获取成功",
                success = true,
                response = data.OrderBy(x => x.StationCode).ToList()
            };
        }


        #endregion

    }
}
